import logging

from PySide6.QtCore import Qt, QUrl
from PySide6.QtGui import QDesktopServices
from PySide6.QtWidgets import (
    QApplication,
    QComboBox,
    QDialog,
    QFileDialog,
    QFormLayout,
    QHBoxLayout,
    QHeaderView,
    QLabel,
    QLineEdit,
    QMenu,
    QMessageBox,
    QPushButton,
    QVBoxLayout,
)

from src.config import Config
from src.models import (
    BenkeRecord,
    BoshiRecord,
    FormerGraduateRecord,
    FreshGraduateRecord,
    HistoryMailRecord,
    PrintRecord,
    ShuoshiRecord,
)
from src.ui.button_delegate import ButtonDelegate
from src.ui.default_delegate import DefaultDelegate
from src.ui.main_ui import Ui_MainWindow
from src.ui.pagination_table_widget import PaginationTableWidget
from src.ui.print_list_ui import Ui_Dialog as PrintListDialog
from src.ui.simple_memory_model import SimpleMemoryModel
from src.utils.add_to_history import add_records_to_history
from src.utils.import_excel_data import (
    import_benke_data,
    import_boshi_data,
    import_ems_data,
    import_former_data,
    import_fresh_data,
    import_shuoshi_data,
)
from src.utils.utils import (
    IN_PRINT_LIST_IDS,
    check_graduate_records_ready,
    do_mail_merge_and_generate_kuaidi_xlsx,
    generate_print_record,
    normalize_path,
)

print_list_ui_inst = PrintListDialog()

main_ui_inst = Ui_MainWindow()


logger = logging.getLogger("src.ui")


def preprocess_print_list_ui(
    print_list_ui: PrintListDialog, config: Config, MainWindow
):
    print_list_ui.setupUi(MainWindow)
    print_list_model = SimpleMemoryModel(
        PrintRecord,
        MainWindow,
        non_data_fields_dict={
            "operation": "操作",
        },
    )
    print_list_ui.tableView.setModel(print_list_model)
    print_list_ui.tableView.horizontalHeader().setSectionResizeMode(
        QHeaderView.ResizeMode.ResizeToContents
    )
    print_list_ui.tableView.horizontalHeader().setStretchLastSection(True)
    print_list_ui.tableView.setItemDelegate(
        DefaultDelegate(PrintRecord, print_list_ui.tableView)
    )
    print_list_ui.tableView.setItemDelegateForColumn(
        print_list_model.get_column_index("operation"),
        ButtonDelegate(
            button_texts=["打印", "删除"],
            parent=print_list_ui.tableView,
        ),
    )


def setup_print_list_ui(print_list_ui: PrintListDialog, config: Config, parent_window):
    preprocess_print_list_ui(print_list_ui, config, parent_window)
    print_list_model = print_list_ui.tableView.model()

    def on_click_cancel_btn():
        parent_window.close()

    def _handle_do_mail_merge_and_generate_kuaidi_xlsx_result(res):
        if res:
            np = normalize_path(config.output_dir)
            msg_box = QMessageBox(parent=parent_window)
            msg_box.setIcon(QMessageBox.Icon.Information)
            msg_box.setWindowTitle("成功")
            msg_box.setText(f"成功生成打印文件，请检查输出目录：\n{np}")
            open_btn = QPushButton("打开输出目录")
            open_btn.clicked.connect(
                lambda: QDesktopServices.openUrl(QUrl.fromLocalFile(np))
            )
            msg_box.addButton(open_btn, QMessageBox.ButtonRole.AcceptRole)

            msg_box.setStandardButtons(QMessageBox.StandardButton.Cancel)
            # 获取按钮并修改文本
            close_btn = msg_box.button(QMessageBox.StandardButton.Cancel)
            close_btn.setText("取消")
            msg_box.exec()

        else:
            QMessageBox.warning(
                parent_window,
                "失败",
                "生成打印文件和快递单文件失败，请检查日志文件",
            )

    def on_click_printall_btn():
        print_list_model = print_list_ui.tableView.model()
        print_records = []
        graduate_records = []
        if isinstance(print_list_model, SimpleMemoryModel):
            for row in range(print_list_model.rowCount()):
                index = print_list_model.index(row, 0)
                graduate_record = print_list_model.get_item(
                    index, Qt.ItemDataRole.UserRole
                )
                print_record = print_list_model.get_item(index)
                if isinstance(
                    graduate_record, (FormerGraduateRecord, FreshGraduateRecord)
                ) and isinstance(print_record, PrintRecord):
                    print_records.append(print_record)
                    graduate_records.append(graduate_record)
            if not print_records or not graduate_records:
                QMessageBox.warning(
                    parent_window,
                    "警告",
                    "没有要打印的记录",
                )
                return
            res = do_mail_merge_and_generate_kuaidi_xlsx(
                config,
                print_records,
                graduate_records,
            )
            _handle_do_mail_merge_and_generate_kuaidi_xlsx_result(res)

    def on_click_operation_btn(index, button_index):
        print_list_model = print_list_ui.tableView.model()
        if isinstance(print_list_model, SimpleMemoryModel):
            if button_index == 0:  # 打印
                graduate_record = print_list_model.get_item(
                    index, Qt.ItemDataRole.UserRole
                )
                print_record = print_list_model.get_item(index)
                if isinstance(
                    graduate_record, (FormerGraduateRecord, FreshGraduateRecord)
                ) and isinstance(print_record, PrintRecord):
                    res = do_mail_merge_and_generate_kuaidi_xlsx(
                        config,
                        [print_record],
                        [graduate_record],
                    )
                    _handle_do_mail_merge_and_generate_kuaidi_xlsx_result(res)
            elif button_index == 1:  # 删除
                graduate_record = print_list_model.get_item(
                    index, Qt.ItemDataRole.UserRole
                )
                if isinstance(
                    graduate_record, (FormerGraduateRecord, FreshGraduateRecord)
                ):
                    IN_PRINT_LIST_IDS.remove(graduate_record.id)
                    # graduate_record.in_print_list = False
                print_list_model.remove_item(index)

    def on_click_delete_all_btn():
        print_list_model = print_list_ui.tableView.model()
        if isinstance(print_list_model, SimpleMemoryModel):
            if print_list_model.rowCount() == 0:
                QMessageBox.warning(
                    parent_window,
                    "警告",
                    "没有要删除的记录",
                )
                return
            if (
                QMessageBox.question(
                    parent_window,
                    "确认删除所有记录",
                    "确定要删除所有记录吗？",
                    QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                )
                == QMessageBox.StandardButton.Yes
            ):
                for row in range(print_list_model.rowCount()):
                    index = print_list_model.index(row, 0)
                    graduate_record = print_list_model.get_item(
                        index, Qt.ItemDataRole.UserRole
                    )
                    if isinstance(
                        graduate_record, (FormerGraduateRecord, FreshGraduateRecord)
                    ):
                        # graduate_record.in_print_list = False
                        IN_PRINT_LIST_IDS.remove(graduate_record.id)
                print_list_model.remove_all_items()

    print_list_ui.cancel_btn.clicked.connect(on_click_cancel_btn)
    print_list_ui.printall_btn.clicked.connect(on_click_printall_btn)
    print_list_ui.deleteall_btn.clicked.connect(on_click_delete_all_btn)
    if isinstance(print_list_model, SimpleMemoryModel):
        delegate = print_list_ui.tableView.itemDelegateForColumn(
            print_list_model.get_column_index("operation")
        )
        if isinstance(delegate, ButtonDelegate):
            delegate.buttonClicked.connect(on_click_operation_btn)


def preprocess_main_ui(main_ui: Ui_MainWindow, config: Config, MainWindow):
    main_ui.setupUi(MainWindow)
    benke_page_table_widget = PaginationTableWidget(
        db_path=config.db_path,
        model_class=BenkeRecord,
        parent=main_ui.benketab,
        filter_fields=["id", "name"],
    )
    benke_page_table_widget.init_table_model(
        global_delegate=DefaultDelegate(BenkeRecord, benke_page_table_widget.tableView),
        # non_data_fields_dict={
        #     "operation": "操作",
        # },
        # delegates_dict={
        #     "operation": ButtonDelegate(
        #         button_texts=["设置党员档案状态"],
        #         parent=benke_page_table_widget.tableView,
        #     ),
        # },
    )
    benke_menu = QMenu(main_ui.benke_tool_btn)
    benke_menu.addActions(
        [
            main_ui.actionexportdata,
        ]
    )
    main_ui.benke_tool_btn.setMenu(benke_menu)
    main_ui.benkeLayout.addWidget(benke_page_table_widget)
    boshi_page_table_widget = PaginationTableWidget(
        db_path=config.db_path,
        model_class=BoshiRecord,
        parent=main_ui.boshitab,
        filter_fields=["id", "name"],
    )
    boshi_page_table_widget.init_table_model(
        global_delegate=DefaultDelegate(BoshiRecord, boshi_page_table_widget.tableView),
        # non_data_fields_dict={
        #     "operation": "操作",
        # },
        # delegates_dict={
        #     "operation": ButtonDelegate(
        #         button_texts=["设置党员档案状态"],
        #         parent=boshi_page_table_widget.tableView,
        #     ),
        # },
    )
    boshi_menu = QMenu(main_ui.boshi_tool_btn)
    boshi_menu.addActions(
        [
            main_ui.actionexportdata,
        ]
    )
    main_ui.boshi_tool_btn.setMenu(boshi_menu)
    main_ui.boshiLayout.addWidget(boshi_page_table_widget)
    shuoshi_page_table_widget = PaginationTableWidget(
        db_path=config.db_path,
        model_class=ShuoshiRecord,
        parent=main_ui.shuoshitab,
        filter_fields=["id", "name"],
    )
    shuoshi_page_table_widget.init_table_model(
        global_delegate=DefaultDelegate(
            ShuoshiRecord, shuoshi_page_table_widget.tableView
        ),
        # non_data_fields_dict={
        #     "operation": "操作",
        # },
        # delegates_dict={
        #     "operation": ButtonDelegate(
        #         button_texts=["设置党员档案状态"],
        #         parent=shuoshi_page_table_widget.tableView,
        #     ),
        # },
    )
    shuoshi_menu = QMenu(main_ui.shuoshi_tool_btn)
    shuoshi_menu.addActions(
        [
            main_ui.actionexportdata,
        ]
    )
    main_ui.shuoshi_tool_btn.setMenu(shuoshi_menu)
    main_ui.shuoshiLayout.addWidget(shuoshi_page_table_widget)
    fresh_mail_page_table_widget = PaginationTableWidget(
        db_path=config.db_path,
        model_class=FreshGraduateRecord,
        parent=main_ui.freshmailtab,
        filter_fields=["id", "name"],
    )
    fresh_mail_page_table_widget.init_table_model(
        non_data_fields_dict={
            "operation": "操作",
        },
        global_delegate=DefaultDelegate(
            FreshGraduateRecord, fresh_mail_page_table_widget.tableView
        ),
        delegates_dict={
            "operation": ButtonDelegate(
                button_texts=["添加到打印列表", "转移到已邮寄列表"],
                parent=fresh_mail_page_table_widget.tableView,
            ),
        },
    )
    fresh_menu = QMenu(main_ui.fresh_tool_btn)
    fresh_menu.addActions(
        [
            main_ui.actionexportdata,
            main_ui.actionopenprintlist,
            main_ui.actionaddalltoprintlist,
            main_ui.actionaddalltohistoryfresh,
        ]
    )
    main_ui.fresh_tool_btn.setMenu(fresh_menu)
    main_ui.freshmailLayout.addWidget(fresh_mail_page_table_widget)

    former_mail_page_table_widget = PaginationTableWidget(
        db_path=config.db_path,
        model_class=FormerGraduateRecord,
        parent=main_ui.formermailtab,
        filter_fields=["id", "name"],
    )
    former_mail_page_table_widget.init_table_model(
        non_data_fields_dict={
            "operation": "操作",
        },
        global_delegate=DefaultDelegate(
            FormerGraduateRecord, former_mail_page_table_widget.tableView
        ),
        delegates_dict={
            "operation": ButtonDelegate(
                button_texts=["添加到打印列表", "转移到已邮寄列表"],
                parent=former_mail_page_table_widget.tableView,
            ),
        },
    )
    main_ui.formermailLayout.addWidget(former_mail_page_table_widget)
    former_menu = QMenu(main_ui.former_tool_btn)
    former_menu.addActions(
        [
            main_ui.actionexportdata,
            main_ui.actionopenprintlist,
            main_ui.actionaddalltoprintlist,
            main_ui.actionaddalltohistoryformer,
        ]
    )
    main_ui.former_tool_btn.setMenu(former_menu)

    history_mail_page_table_widget = PaginationTableWidget(
        db_path=config.db_path,
        model_class=HistoryMailRecord,
        parent=main_ui.historymailtab,
        filter_fields=["stu_id", "name"],
    )
    history_mail_page_table_widget.init_table_model(
        global_delegate=DefaultDelegate(
            HistoryMailRecord, history_mail_page_table_widget.tableView
        ),
    )
    history_menu = QMenu(main_ui.history_tool_btn)
    history_menu.addActions(
        [
            main_ui.actionexportdata,
        ]
    )
    main_ui.history_tool_btn.setMenu(history_menu)
    main_ui.historymailLayout.addWidget(history_mail_page_table_widget)


def setup_main_ui(main_ui: Ui_MainWindow, config: Config, MainWindow):
    # 预处理
    preprocess_main_ui(main_ui, config, MainWindow)
    print_list_dialog = QDialog(MainWindow)
    setup_print_list_ui(print_list_ui_inst, config, print_list_dialog)

    # 绑定槽函数
    def on_searchbtn_clicked():
        search_text = main_ui.lineEdit.text()
        # 获取当前选中的tab和其中的table_widget
        current_tab = main_ui.tabWidget.currentWidget()
        current_table_widget = current_tab.findChild(PaginationTableWidget)
        if current_table_widget:
            current_table_widget.search_id_or_name(search_text)

    def on_print_list_btn_clicked():
        print_list_dialog.exec()

    def on_tab_changed(index):
        """当标签页切换时，重置当前表格的水平滚动条位置"""
        current_tab = main_ui.tabWidget.widget(index)
        current_table_widget = current_tab.findChild(PaginationTableWidget)
        if current_table_widget:
            # 重置水平滚动条到最左侧
            current_table_widget.tableView.horizontalScrollBar().setValue(0)

    def on_handle_mail_btn_clicked(index, button_index):
        if button_index == 0:
            # TODO 检查本科硕士博士信息表中的就绪情况
            model = print_list_ui_inst.tableView.model()
            if isinstance(model, SimpleMemoryModel):
                current_tab = main_ui.tabWidget.currentWidget()
                current_table_widget = current_tab.findChild(PaginationTableWidget)
                if current_table_widget:
                    row_data = current_table_widget.proxy_table_model.getItem(index)
                    if isinstance(
                        row_data, (FreshGraduateRecord, FormerGraduateRecord)
                    ):
                        # if not row_data.in_print_list:
                        if row_data.id not in IN_PRINT_LIST_IDS:
                            succ_records, fail_records, fail_reasons = (
                                check_graduate_records_ready(
                                    [row_data],
                                    current_table_widget.source_table_model.conn,
                                )
                            )
                            if not succ_records and not fail_records:
                                QMessageBox.warning(
                                    MainWindow,
                                    "警告",
                                    "没有合法记录可以添加到打印列表，请检查本硕博信息表中是否存在对应同学。",
                                )
                                return
                            for record in succ_records:
                                # record.in_print_list = True
                                IN_PRINT_LIST_IDS.add(record.id)
                                print_record = generate_print_record(record)
                                model.add_item(print_record, record)
                            if fail_records:
                                QMessageBox.warning(
                                    MainWindow,
                                    "警告",
                                    f"已成功添加{len(succ_records)}条记录，但下列记录未就绪：\n"
                                    + "\n".join(
                                        [
                                            f"{record.id} {record.name}: {reason}"
                                            for record, reason in zip(
                                                fail_records, fail_reasons
                                            )
                                        ]
                                    ),
                                )
                        else:
                            QMessageBox.warning(
                                MainWindow,
                                "警告",
                                "该记录已在打印列表中，无需重复添加。",
                            )
        elif button_index == 1:
            # 转移到已邮寄列表
            current_tab = main_ui.tabWidget.currentWidget()
            current_table_widget = current_tab.findChild(PaginationTableWidget)
            if current_table_widget:
                row_data = current_table_widget.proxy_table_model.getItem(index)
                if isinstance(row_data, (FreshGraduateRecord, FormerGraduateRecord)):
                    # 创建一个输入dialog，布局为formlayout，要求填入tracking_number和类型
                    dialog = QDialog(MainWindow)
                    dialog.setWindowTitle("输入")
                    layout = QFormLayout()
                    tracking_number_input = QLineEdit()
                    type_input = QComboBox()
                    type_input.addItems(["EMS", "机要"])
                    layout.addRow("类型:", type_input)
                    layout.addRow("EMS号/机要号:", tracking_number_input)

                    # 创建accepted button
                    accept_button = QPushButton("确认", dialog)
                    accept_button.clicked.connect(lambda: dialog.accept())
                    layout.addWidget(accept_button)
                    dialog.setLayout(layout)

                    if dialog.exec() == QDialog.DialogCode.Accepted:
                        tracking_number = tracking_number_input.text()
                        record_type = type_input.currentText()
                    else:
                        return
                    history_mail_page_table_widget = main_ui.historymailtab.findChild(
                        PaginationTableWidget
                    )
                    benke_page_table_widget = main_ui.benketab.findChild(
                        PaginationTableWidget
                    )
                    shuoshi_page_table_widget = main_ui.shuoshitab.findChild(
                        PaginationTableWidget
                    )
                    boshi_page_table_widget = main_ui.boshitab.findChild(
                        PaginationTableWidget
                    )
                    if (
                        history_mail_page_table_widget
                        and benke_page_table_widget
                        and shuoshi_page_table_widget
                        and boshi_page_table_widget
                    ):
                        history_mail_page_table_widget.update_pagination_controls()
                        add_records_to_history(
                            [row_data],
                            history_mail_page_table_widget.proxy_table_model,
                            current_table_widget.proxy_table_model,
                            [tracking_number],
                            record_type,
                        )
                        benke_page_table_widget.on_refresh()
                        shuoshi_page_table_widget.on_refresh()
                        boshi_page_table_widget.on_refresh()

    def on_add_all_to_history_action_triggered():
        current_tab = main_ui.tabWidget.currentWidget()
        current_table_widget = current_tab.findChild(PaginationTableWidget)
        if not current_table_widget:
            return
        if current_table_widget.proxy_table_model.rowCount() == 0:
            QMessageBox.warning(
                MainWindow,
                "警告",
                "没有要转移到历史邮寄档案的记录",
            )
            return
        file_path, _ = QFileDialog.getOpenFileName(
            MainWindow,
            "选择保存EMS号码的Excel文件",
            config.output_dir,
            "Excel文件 (*.xlsx *.xls)",
        )
        if not file_path:
            return
        ems_records = import_ems_data(file_path)
        history_mail_page_table_widget = main_ui.historymailtab.findChild(
            PaginationTableWidget
        )
        benke_page_table_widget = main_ui.benketab.findChild(PaginationTableWidget)
        shuoshi_page_table_widget = main_ui.shuoshitab.findChild(PaginationTableWidget)
        boshi_page_table_widget = main_ui.boshitab.findChild(PaginationTableWidget)
        row_data_list = current_table_widget.proxy_table_model.get_all_models()
        if (
            history_mail_page_table_widget
            and benke_page_table_widget
            and shuoshi_page_table_widget
            and boshi_page_table_widget
        ):
            add_records_to_history(
                row_data_list,
                history_mail_page_table_widget.proxy_table_model,
                current_table_widget.proxy_table_model,
                ems_records,
                "EMS",
            )
            benke_page_table_widget.on_refresh()
            shuoshi_page_table_widget.on_refresh()
            boshi_page_table_widget.on_refresh()

    def open_help_page():
        url = config.help_url
        QDesktopServices.openUrl(QUrl(url))

    def open_fahuo_url():
        npath = normalize_path(config.output_dir)
        dialog = QDialog(MainWindow)
        dialog.setWindowTitle("发货平台信息")

        # 创建布局和内容
        layout = QVBoxLayout()
        label = QLabel(f"发货平台：{config.fahuo_url}\n生成文件保存路径：{npath}")
        layout.addWidget(label)

        # 创建按钮
        btn1 = QPushButton("打开发货平台", dialog)
        btn1.clicked.connect(
            lambda: [QDesktopServices.openUrl(QUrl(config.fahuo_url)), dialog.close()]
        )

        btn2 = QPushButton("打开保存路径", dialog)
        btn2.clicked.connect(
            lambda: [
                QDesktopServices.openUrl(QUrl.fromLocalFile(npath)),
                dialog.close(),
            ]
        )

        btn3 = QPushButton("复制保存路径", dialog)
        btn3.clicked.connect(
            lambda: [
                QApplication.clipboard().setText(npath),
                QMessageBox.information(MainWindow, "提示", "路径已复制到剪贴板"),
            ]
        )
        hlayout = QHBoxLayout()
        hlayout.addWidget(btn1)
        hlayout.addWidget(btn2)
        hlayout.addWidget(btn3)
        layout.addLayout(hlayout)

        dialog.setLayout(layout)
        dialog.exec()

    def on_delete_batch_btn_clicked():
        current_tab = main_ui.tabWidget.currentWidget()
        current_table_widget = current_tab.findChild(PaginationTableWidget)
        if not current_table_widget:
            return
        selected_indices = current_table_widget.tableView.selectedIndexes()
        unique_indices = set(index.row() for index in selected_indices)
        if not selected_indices:
            QMessageBox.warning(MainWindow, "警告", "请先选择要删除的项目")
            return
        reply = QMessageBox.question(
            MainWindow,
            "确认删除",
            f"确定要删除选中的{len(unique_indices)}个项目吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No,
        )
        if reply == QMessageBox.StandardButton.Yes:
            current_table_widget.proxy_table_model.delete_batch(selected_indices)

    def on_add_one_row_btn_clicked():
        current_tab = main_ui.tabWidget.currentWidget()
        current_table_widget = current_tab.findChild(PaginationTableWidget)
        if current_table_widget:
            current_table_widget.proxy_table_model.handle_add_one_row()

    def on_import_benke_data():
        excel_path = QFileDialog.getOpenFileName(
            MainWindow, "选择本科生数据文件", "", "Excel 文件 (*.xlsx *.xls)"
        )[0]
        if not excel_path:
            return
        try:
            benke_records = import_benke_data(excel_path)
            current_tab = main_ui.tabWidget.currentWidget()
            current_table_widget = current_tab.findChild(PaginationTableWidget)
            if not current_table_widget:
                return
            current_table_widget.proxy_table_model.update_or_insert_batch_models(
                benke_records
            )
        except Exception as e:
            QMessageBox.critical(MainWindow, "错误", "导入本科生数据时出错，请查看日志")
            logger.error(f"导入本科生数据时出错：{str(e)}")
            return

    def on_import_shuoshi_data():
        excel_path = QFileDialog.getOpenFileName(
            MainWindow, "选择硕士数据文件", "", "Excel 文件 (*.xlsx *.xls)"
        )[0]
        if not excel_path:
            return
        try:
            shuoshi_records = import_shuoshi_data(excel_path)
            current_tab = main_ui.tabWidget.currentWidget()
            current_table_widget = current_tab.findChild(PaginationTableWidget)
            if not current_table_widget:
                return
            current_table_widget.proxy_table_model.update_or_insert_batch_models(
                shuoshi_records
            )
        except Exception as e:
            QMessageBox.critical(MainWindow, "错误", "导入硕士数据时出错，请查看日志")
            logger.error(f"导入硕士数据时出错：{str(e)}")
            return

    def on_import_boshi_data():
        excel_path = QFileDialog.getOpenFileName(
            MainWindow, "选择博士数据文件", "", "Excel 文件 (*.xlsx *.xls)"
        )[0]
        if not excel_path:
            return
        try:
            boshi_records = import_boshi_data(excel_path)
            current_tab = main_ui.tabWidget.currentWidget()
            current_table_widget = current_tab.findChild(PaginationTableWidget)
            if not current_table_widget:
                return
            current_table_widget.proxy_table_model.update_or_insert_batch_models(
                boshi_records
            )
        except Exception as e:
            QMessageBox.critical(MainWindow, "错误", "导入博士数据时出错，请查看日志")
            logger.error(f"导入博士数据时出错：{str(e)}")
            return

    def on_import_fresh_data():
        excel_path = QFileDialog.getOpenFileName(
            MainWindow, "选择新数据文件", "", "Excel 文件 (*.xlsx *.xls)"
        )[0]
        if not excel_path:
            return
        try:
            fresh_records = import_fresh_data(excel_path)
            current_tab = main_ui.tabWidget.currentWidget()
            current_table_widget = current_tab.findChild(PaginationTableWidget)
            if not current_table_widget:
                return
            current_table_widget.proxy_table_model.update_or_insert_batch_models(
                fresh_records
            )
        except Exception as e:
            QMessageBox.critical(
                MainWindow, "错误", "导入应届邮递数据时出错，请查看日志"
            )
            logger.error(f"导入新数据时出错：{str(e)}")
            return

    def on_import_former_data():
        excel_path = QFileDialog.getOpenFileName(
            MainWindow, "选择旧数据文件", "", "Excel 文件 (*.xlsx *.xls)"
        )[0]
        if not excel_path:
            return
        try:
            former_records = import_former_data(excel_path)
            current_tab = main_ui.tabWidget.currentWidget()
            current_table_widget = current_tab.findChild(PaginationTableWidget)
            if not current_table_widget:
                return
            current_table_widget.proxy_table_model.update_or_insert_batch_models(
                former_records
            )
        except Exception as e:
            QMessageBox.critical(MainWindow, "错误", "导入往邮递数据时出错，请查看日志")
            logger.error(f"导入旧数据时出错：{str(e)}")
            return

    def on_export_data_to_excel_btn_clicked():
        current_tab = main_ui.tabWidget.currentWidget()
        current_table_widget = current_tab.findChild(PaginationTableWidget)
        if not current_table_widget:
            return
        file_path = QFileDialog.getSaveFileName(
            MainWindow, "导出数据到表格", "", "Excel 文件 (*.xlsx *.xls)"
        )[0]
        if not file_path:
            return
        current_table_widget.proxy_table_model.export_to_excel(file_path)

    def on_add_all_to_print_list_action_triggered():
        # TODO 检查本科硕士博士信息表中的就绪情况
        model = print_list_ui_inst.tableView.model()
        if isinstance(model, SimpleMemoryModel):
            current_tab = main_ui.tabWidget.currentWidget()
            current_table_widget = current_tab.findChild(PaginationTableWidget)
            if current_table_widget:
                records = current_table_widget.proxy_table_model.get_all_models()
                records = [
                    record for record in records if record.id not in IN_PRINT_LIST_IDS
                ]
                if not records:
                    QMessageBox.warning(
                        MainWindow,
                        "警告",
                        "没有记录可以添加到打印列表。",
                    )
                    return
                (
                    succ_records,
                    fail_records,
                    fail_reasons,
                ) = check_graduate_records_ready(
                    records, current_table_widget.source_table_model.conn
                )
                if not succ_records and not fail_records:
                    QMessageBox.warning(
                        MainWindow,
                        "警告",
                        "没有合法记录可以添加到打印列表，请检查本硕博信息表中是否存在对应同学。",
                    )
                    return
                for record in succ_records:
                    print_record = generate_print_record(record)
                    model.add_item(print_record, record)
                    # record.in_print_list = True
                    IN_PRINT_LIST_IDS.add(record.id)
                if fail_records:
                    QMessageBox.warning(
                        MainWindow,
                        "警告",
                        f"已成功添加{len(succ_records)}条记录，但下列记录未就绪：\n"
                        + "\n".join(
                            [
                                f"{record.id} {record.name}: {reason}"
                                for record, reason in zip(fail_records, fail_reasons)
                            ]
                        ),
                    )
                else:
                    QMessageBox.information(
                        MainWindow,
                        "提示",
                        "所有记录已添加到打印列表。",
                    )

    # 定义信号槽连接
    main_ui.searchbtn.clicked.connect(on_searchbtn_clicked)
    main_ui.actionopenprintlist.triggered.connect(on_print_list_btn_clicked)
    main_ui.actionexportdata.triggered.connect(on_export_data_to_excel_btn_clicked)
    fresh_mail_page_table_widget = main_ui.freshmailtab.findChild(PaginationTableWidget)
    if fresh_mail_page_table_widget:
        delegate = fresh_mail_page_table_widget.tableView.itemDelegateForColumn(
            fresh_mail_page_table_widget.proxy_table_model.get_column_index("operation")
        )
        if isinstance(delegate, ButtonDelegate):
            delegate.buttonClicked.connect(on_handle_mail_btn_clicked)
    former_mail_page_table_widget = main_ui.formermailtab.findChild(
        PaginationTableWidget
    )
    if former_mail_page_table_widget:
        delegate = former_mail_page_table_widget.tableView.itemDelegateForColumn(
            former_mail_page_table_widget.proxy_table_model.get_column_index(
                "operation"
            )
        )
        if isinstance(delegate, ButtonDelegate):
            delegate.buttonClicked.connect(on_handle_mail_btn_clicked)
    main_ui.actionopenfahuourl.triggered.connect(open_fahuo_url)
    main_ui.actionopenhelppage.triggered.connect(open_help_page)
    main_ui.actionaddalltoprintlist.triggered.connect(
        on_add_all_to_print_list_action_triggered
    )
    main_ui.delete_selected_fresh_btn.clicked.connect(on_delete_batch_btn_clicked)
    main_ui.delete_selected_former_btn.clicked.connect(on_delete_batch_btn_clicked)
    main_ui.delete_selected_shuoshi_btn.clicked.connect(on_delete_batch_btn_clicked)
    main_ui.delete_selected_boshi_btn.clicked.connect(on_delete_batch_btn_clicked)
    main_ui.delete_selected_history_btn.clicked.connect(on_delete_batch_btn_clicked)
    main_ui.delete_selected_benke_btn.clicked.connect(on_delete_batch_btn_clicked)

    main_ui.add_one_shuoshi_btn.clicked.connect(on_add_one_row_btn_clicked)
    main_ui.add_one_boshi_btn.clicked.connect(on_add_one_row_btn_clicked)
    main_ui.add_one_benke_btn.clicked.connect(on_add_one_row_btn_clicked)
    main_ui.add_one_fresh_btn.clicked.connect(on_add_one_row_btn_clicked)
    main_ui.add_one_former_btn.clicked.connect(on_add_one_row_btn_clicked)
    main_ui.add_one_history_btn.clicked.connect(on_add_one_row_btn_clicked)
    main_ui.import_benke_data.clicked.connect(on_import_benke_data)
    main_ui.import_shuoshi_data.clicked.connect(on_import_shuoshi_data)
    main_ui.import_boshi_data.clicked.connect(on_import_boshi_data)
    main_ui.import_fresh_data.clicked.connect(on_import_fresh_data)
    main_ui.import_former_data.clicked.connect(on_import_former_data)
    main_ui.actionaddalltohistoryfresh.triggered.connect(
        on_add_all_to_history_action_triggered
    )
    main_ui.actionaddalltohistoryformer.triggered.connect(
        on_add_all_to_history_action_triggered
    )
    # 连接标签页切换信号
    main_ui.tabWidget.currentChanged.connect(on_tab_changed)
